package com.example.myblog_sm.controller;

import com.example.myblog_sm.common.Result;
import com.example.myblog_sm.common.SessionUtils;
import com.example.myblog_sm.config.ThreadPoolConfig;
import com.example.myblog_sm.model.Articleinfo;
import com.example.myblog_sm.model.Userinfo;
import com.example.myblog_sm.model.Vo.UserinfoVo;
import com.example.myblog_sm.service.ArticleService;
import com.example.myblog_sm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    private static final int _LENGTH_ = 120;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private UserService userService;
    /**
     * 得到登录用户的文章列表
     * @return
     */
    @RequestMapping("/mylist")
    public Result myList(HttpServletRequest request){
        //1.得到当前用户
        Userinfo userinfo = SessionUtils.getUser(request);
        if (userinfo == null) {
            return Result.fail(-1, "请先登录！");
        }
        // 2.根据用户 id 查询此用户发表的所有文章
        List<Articleinfo> list = articleService.getListByUid(userinfo.getId());
        // 处理 list -> 将文章正文变成简介
        if (list != null && list.size() > 0) {
            // 并行处理 list 集合
            list.stream().parallel().forEach((art) -> {
                if (art.getContent().length() > _LENGTH_) {
                    art.setContent(art.getContent().substring(0, _LENGTH_));
                }
            });
        }
        // 3.返回给前端
        return Result.succ(list);
    }
    /**
     * 删除文章
     */
    @RequestMapping("/del")
    public Result del(Integer aid,HttpServletRequest request){
        //1.参数效验
        if(aid == null || aid <= 0){
            return Result.fail(-1,"参数错误！");
        }
        //2.得到当前登录用户
        Userinfo userinfo = SessionUtils.getUser(request);
        if(userinfo == null){
            return Result.fail(-1,"请先登录！");
        }
        //3.判断文章的归属人和删除操作合并到一起
        //4.删除操作
        int result = articleService.del(aid,userinfo.getId());
        //5.将结果返回给前端
        return Result.succ(result);
    }
    @RequestMapping("/add")
    public Result add(HttpServletRequest request,Articleinfo articleinfo){
        //1.效验参数
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getContent()) ||
        !StringUtils.hasLength(articleinfo.getTitle())){
            return Result.fail(-1,"非法参数");
        }
        //2.组装参数
        Userinfo userinfo = SessionUtils.getUser(request);
        if(userinfo == null){
            return Result.fail(-2,"未登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        //3.写入数据库
        int result = articleService.add(articleinfo);
        //4.结果返回给前端
        return Result.succ(result);
    }
    /**
     *
     */
    @RequestMapping("/update_init")
    public Result updateInit(Integer aid,HttpServletRequest request){
        //1.参数效验
        if(aid == null || aid <= 0){
            return Result.fail(-1,"参数有误");
        }
        //2.得到用户id
        Userinfo userinfo = SessionUtils.getUser(request);
        if(userinfo == null){
            return Result.fail(-2,"请先登录！");
        }
        //3.查询文章并效验权限
        Articleinfo articleinfo = articleService.getArticleByIdAndUid(aid,userinfo.getId());
        return Result.succ(articleinfo);
    }

    /**
     * 修改文章
     * @param articleinfo
     * @param request
     * @return
     */
    @RequestMapping("/update")
    public Result update(Articleinfo articleinfo,HttpServletRequest request){
        //1.参数效验
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())||
        !StringUtils.hasLength(articleinfo.getContent()) || articleinfo.getId() == 0){
            return Result.fail(-1,"非法参数!");
        }
        //2.获取登录用户信息
        Userinfo userinfo = SessionUtils.getUser(request);
        if(userinfo == null){
            return Result.fail(-2,"请先登录");
        }
        //3.进行修改操作
        articleinfo.setUid(userinfo.getId());
        int result = articleService.update(articleinfo);
        //4.参数返回给前端
        return Result.succ(result);
    }
    /**
     * 查询文章详情页
     */
    @RequestMapping("/detail")
    public Result detail(Integer aid) throws ExecutionException, InterruptedException {
        //1.参数效验
        if(aid == null || aid == 0){
            return Result.fail(-1,"参数错误");
        }
        //2.查询文章详情
        Articleinfo articleinfo = articleService.getDetail(aid);
        if (articleinfo == null || articleinfo.getId() <= 0){
            return Result.fail(-1,"非法参数!");
        }

        //3.根据uid查询用户的详情
        FutureTask<UserinfoVo> userTask = new FutureTask<>(()->{
            // 调用service
            return userService.getUserById(articleinfo.getUid());
        });
        taskExecutor.submit(userTask);
        //4.根据uid查询用户发表的总文章数
        FutureTask<Integer> artCountTask = new FutureTask<>(()->{
           return articleService.getArticleCountByUid(articleinfo.getUid());
        });
        //组装数据
        taskExecutor.submit(artCountTask);
        UserinfoVo userinfoVo = userTask.get();// 等待任务（线程池）执行完成
        int artCount = artCountTask.get();
        userinfoVo.setArtCount(artCount);
        HashMap<String,Object> result = new HashMap<>();
        result.put("user",userinfoVo);
        result.put("art",articleinfo);
        //5.组装数据
        return Result.succ(result);
    }
    @RequestMapping("/increment_rcount")
    public Result increment(Integer aid){
        //效验参数
        if(aid <= 0 || aid == null ){
            return Result.fail(-1,"参数有误!");
        }
        //更改数据库
        int result = articleService.increment(aid);
        //返回结果
        return Result.succ(result);
    }
    @RequestMapping("/getlistbypage")
    public Result getlistbypage(Integer pindex,Integer psize) throws ExecutionException, InterruptedException {
        //1.加工参数
        if(pindex == null || pindex < 1 ){
            pindex = 1;
        }
        if(psize == null || psize< 1 ){
            psize = 2;
        }
        //2.并发进行文章列表和总页数的查询
        //2.1查询分页列表数据
        Integer finalPsize = psize;
        Integer finalPindex = pindex;
        int pz = psize;
        FutureTask<List<Articleinfo>> getArtListTask = new FutureTask<>(()->{
            int offset = finalPsize *(finalPindex -1);
            return articleService.getListPageById(pz,offset);
        });
        //2.2 查询总页数
        FutureTask<Integer> sizeTask = new FutureTask<>(()->{
           int totalCount = articleService.getCount();
           //页数向上取整
            double sizeTemp = (totalCount * 1.0 )/(pz*1.0);
            return (int)Math.ceil(sizeTemp);
        });
        //3.组装数据
        taskExecutor.submit(getArtListTask);
        taskExecutor.submit(sizeTask);
        List<Articleinfo> list = getArtListTask.get();
        int size = sizeTask.get();
        HashMap<String,Object> hashMap= new HashMap<>();
        hashMap.put("list",list);
        hashMap.put("size",size);
        //4.将结果返回给前端
        return Result.succ(hashMap);
    }
}
